require 'View/UIBase/UIBase'

UIActivityDraw = UIBase.New(PanelNames.UIActivityDraw)
local _M = UIActivityDraw

function _M.Init(func, id)
    _M.activeId = id
    UIBase.Init(_M, func)
end

function _M:OnCreate()
    if not _M.hasInit then
        _M.hasInit = true
        self:initView()
        self:addEvent()
    end
end

function _M:initView()
    self.getAniTime = 2000 -- 获得特效时间,毫秒
    self.HeroBgIcon = self:GetChild("HeroBgIcon")
    self.txt_title = self:GetChild("title")
    self.btn_back = self:GetChild("Backbtn")
    self.com_coin_lb = self:GetChild("CoinLb")
    self.com_coin_lb1 = self:GetChild("CoinLb1")
    self.draw_wrapper = GoWrapper.New()
    self.lihui = self:GetChild("lihui")
    self.tips = self:GetChild("tips")

    self.btn_draw1 = self:GetChild("btndraw1")
    self.icon_draw1_cost = self.btn_draw1:GetChild("cost")
    self.txt_draw1_num = self.btn_draw1:GetChild("num1")
    self.txt_draw1_title = self.btn_draw1:GetChild("title")
    self.btn_draw2 = self:GetChild("btndraw10")
    self.icon_draw2_cost = self.btn_draw2:GetChild("cost")
    self.txt_draw2_num = self.btn_draw2:GetChild("num1")
    self.txt_draw2_title = self.btn_draw2:GetChild("title")

    self.txt_change_tips = self:GetChild("ChangeTips")
    self.btn_choose_hero = self:GetChild("Buttonhero")
    self.txt_banner = self:GetChild("bannerText")
    self.ShopBtn = self:GetChild("ShopBtn")
    self.HeroBtn = self:GetChild("HeroBtn")
    self.txt_draw_tips = self:GetChild("DrawTips")
    self.effect_xszhaohuan = self:GetChild("effect_xszhaohuan")
    self.maskController = self:GetController("mask")
    self.txt_draw_tips.text = ""

    self.btn_help = self:GetChild("help")

    self.tb_activity = ActiveManager.getActiveTableList(self.activeId)
    self.tb_activity_model = G.dataTable[self.tb_activity.f_ModelName][tostring(self.activeId)]
    self.server_activity_data = ActiveManager.getActiveServerDataList(self.activeId)
    self.txt_title.text = getLanguage(self.tb_activity.f_ActivityName)
    self.com_coin_lb.icon = "ui://ItemAtlas/" .. CurrencyEnum.GOLD
    self.com_coin_lb.text = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.GOLD)

    local server_time = Config.serverTime/1000
    local end_time = self.server_activity_data and self.server_activity_data.endTime or 0
    local dis_time =  end_time - server_time
    if dis_time > 0 then
        self:CloseTimer()
        self.txt_banner.text = string.format(getLanguage("DailyConsumptionBannerTips10201"), getTimeStr(dis_time))
        self.activity_time_id = utimer.timeCall(function()
            dis_time = dis_time -1
            if self.txt_banner then
                local tips_str = string.format(getLanguage("DailyConsumptionBannerTips10201"), getTimeStr(dis_time))
                if self.banner_tips_str == nil or self.banner_tips_str ~= tips_str then
                    self.txt_banner.text =  tips_str
                    self.banner_tips_str = tips_str
                end
            end
            if dis_time <= 0 then
                if self.txt_banner then
                    self.txt_banner.text = getLanguage("Sys_ActivityEnd")
                end
                utimer.remove(self.activity_time_id)
                self.activity_time_id = nil
            end
        end, 1000, dis_time)
    else
        self:OnBack()
        return
    end

    local tb_activitydraw = G.dataTable["t_activitydraw"][tostring(self.activeId)]
    -- print("initView-->", self.activeId, table.tostring(tb_activitydraw) )
    local cfg_draw_item = decodeJsonStrToTabel(tb_activitydraw.f_DrawConsume)
    self.cfg_hero_select = decodeJsonStrToTabel(tb_activitydraw.f_HeroSelect)
    self.cost_cfg_item_id1 = cfg_draw_item[1] and cfg_draw_item[1][1] or 0
    self.cost_cfg_item_id2 = cfg_draw_item[2] and cfg_draw_item[2][1] or 0
    self.draw_left_num = cfg_draw_item[1] and cfg_draw_item[1][3] or 0
    self.draw_right_num = cfg_draw_item[2] and cfg_draw_item[2][3] or 0

    self.cost_item_num1 = cfg_draw_item[1] and cfg_draw_item[1][2] or 0
    self.cost_item_num2 = cfg_draw_item[2] and cfg_draw_item[2][2] or 0
    self.txt_draw1_title.text = string.format("召唤%s次", self.draw_left_num)
    self.txt_draw2_title.text = string.format("召唤%s次", self.draw_right_num)

    local cfg_item1 = G.dataTable["t_item"][tostring(self.cost_cfg_item_id1)]
    local cfg_item2 = G.dataTable["t_item"][tostring(self.cost_cfg_item_id2)]
    -- print("initView--->", table.tostring(cfg_item1) , table.tostring(cfg_item2) )
    self.icon_draw1_cost.url =  "ui://ItemAtlas/" .. cfg_item1.f_Icon
    self.txt_draw1_num.text = string.format("%s", self.cost_item_num1 ) -- ×
    self.icon_draw2_cost.url =  "ui://ItemAtlas/" .. cfg_item2.f_Icon
    self.txt_draw2_num.text = string.format("%s", self.cost_item_num2 )

    self.quickNumData = GetGlobalStringValue(590, true);
    self.cost_item_name1 = getLanguage(cfg_item1.f_ItemName)
    self.cost_item_name2 = getLanguage(cfg_item2.f_ItemName)

    self.com_coin_lb1.icon = "ui://ItemAtlas/" .. cfg_item1.f_Icon
    local own_num = logicMgr.ItemManager.getItemCountbyModelId(tostring(self.cost_cfg_item_id1))
    self.com_coin_lb1.text = tostring(own_num)
    self.ShopBtn.visible = self.tb_activity_model.f_Functionswitchid ~= 0;
    drawHandler.reqTimeLimitDrawInfo( self.activeId ) --获取抽卡信息
end

function _M:RefreshData()
    self.tips.text = string.format(getLanguage("Draw_TimeLimit"), logicMgr.HeroManager.getDrawTodayCount(self.activeId), dataTable.getGlobalInt(616));
    local choose_heroid = drawHandler.ActivityDrawSource.choose_hero_id
    -- print("_M:RefreshData-->choose_heroid:", choose_heroid)
    if choose_heroid == nil or choose_heroid == 0 then
        showUI(PanelNames.UIDrawChoose, false, 2, self.activeId)
        --self:OnBack();
        return
    end
    self:updateCost();
    if self.lihui ~= nil and choose_heroid ~= nil then
        logicMgr.CostManager.updateLiHui(self, self.draw_wrapper, self.lihui, nil, choose_heroid)
    end
    local cfg_hero = logicMgr.HeroManager.GetHeroConfigbyModelId(choose_heroid)
    local remain_times =  drawHandler.ActivityDrawSource.remain_times or 0
    self.tb_activity_model.f_HeroBgIcon = decodeJsonStrToTabel(self.tb_activity_model.f_HeroBgIcon)
    if cfg_hero.f_FactionType == 1 then
        self.HeroBgIcon.url = self.tb_activity_model.f_HeroBgIcon[2]
    elseif cfg_hero.f_FactionType == 2 then
        self.HeroBgIcon.url = self.tb_activity_model.f_HeroBgIcon[3]
    elseif cfg_hero.f_FactionType == 3 then
        self.HeroBgIcon.url = self.tb_activity_model.f_HeroBgIcon[4]
    else
        self.HeroBgIcon.url = self.tb_activity_model.f_HeroBgIcon[1]
    end
    local maxNum = 0;
    for k, v in pairs(self.cfg_hero_select)do
        if v[1] == choose_heroid then
            maxNum = v[2]
        end
    end
    local nowDrawNum = math.max(maxNum - remain_times, 0)
    self.txt_draw_tips.text = string.format(getLanguage(self.tb_activity_model.f_DrawTips), nowDrawNum, maxNum, getLanguage(cfg_hero.f_HeroName))
end

function _M:ShowDrawItem(data)
    self.maskController.selectedIndex = 1;
    local newPartnerModelId = -1
    local partnerModelId = -1
    local get_items = {}
    for _, v in pairs(data) do
        if v.itemModelId == drawHandler.ActivityDrawSource.choose_hero_id then
            local heroData = logicMgr.HeroManager.getHeroDatabyModelId(v.itemModelId,true)
            local heroconfig = G.dataTable["t_hero"][tostring(v.itemModelId)];
            if heroData ~= nil and heroData.isNew then
                local singlereward = {}
                singlereward.itemModelId = 201000 + v.itemModelId
                logicMgr.HeroManager.setHeroIsNew(heroData.partnerId, false)
                newPartnerModelId = v.itemModelId
                table.insert(get_items, singlereward)
            elseif heroData ~= nil and heroconfig ~= nil and heroData.star >=  G.dataTable["t_global"][tostring(93)].f_int_value then
                for k, v in pairs(decodeJsonStrToTabel(heroconfig.f_AutoTrans)) do
                    local singlereward = {}
                    singlereward.itemModelId = v[1]
                    singlereward.num = v[2]
                    table.insert(get_items, singlereward)
                end
            elseif heroconfig ~= nil then
                local singlereward = {}
                singlereward.itemModelId = heroconfig.f_StoneId
                singlereward.num = heroconfig.f_RepeatCount
                table.insert(get_items, singlereward)
            end
            partnerModelId = v.itemModelId
        else
            table.insert(get_items, v)
        end
    end
    Util.PlayAction(self.effect_xszhaohuan.wrapTarget, "idle", false);
    self:TimeCall(function ()
        if partnerModelId == -1 then
            showUI(PanelNames.UICommonItemGet, nil, nil, 2, get_items, nil, nil, true)
        else
            showUI(PanelNames.UIDrawAnimation, partnerModelId, nil, false, function()
                closeUI(PanelNames.UIDrawAnimation)
                showUI(PanelNames.UICommonItemGet, nil, nil, 2, get_items, nil, nil, true)
            end, nil, true, newPartnerModelId == -1)
        end
        self.maskController.selectedIndex = 0;
    end, self.getAniTime);
end

function _M:updateCost()
    if self.cost_cfg_item_id1~=nil and self.com_coin_lb1.text ~= nil then
        local own_num = logicMgr.ItemManager.getItemCountbyModelId(tostring(self.cost_cfg_item_id1))
        self.com_coin_lb1.text = tostring(own_num)
    end
    local own_item1_num = logicMgr.ItemManager.getItemCountbyModelId(self.cost_cfg_item_id1)
    local own_item2_num = logicMgr.ItemManager.getItemCountbyModelId(self.cost_cfg_item_id2)
    if own_item1_num < self.cost_item_num1 then
        self.txt_draw1_num.text = string.format("%s", "[color=#FF0000]" .. self.cost_item_num1 .. "[/color]")
    else
        self.txt_draw1_num.text = string.format("%s", "[color=#FFFFFF]" .. self.cost_item_num1 .. "[/color]")
    end
    if own_item2_num < self.cost_item_num2 then
        self.txt_draw2_num.text = string.format("%s", "[color=#FF0000]" .. self.cost_item_num2 .. "[/color]")
    else
        self.txt_draw2_num.text = string.format("%s", "[color=#FFFFFF]" .. self.cost_item_num2 .. "[/color]")
    end
end
function _M:CloseTimer()
    if self.activity_time_id ~= nil then
        utimer.remove(self.activity_time_id)
        self.activity_time_id = nil
    end
end

function _M:addEvent()
    self:RegisterOnClick(self.btn_back, self.OnBack)
    self:RegisterOnClick(self.btn_draw1, self.OnClickDraw1)
    self:RegisterOnClick(self.btn_draw2, self.OnClickDraw10)
    self:RegisterOnClick(self.btn_choose_hero,  self.OnClickChooseHero)
    self:RegisterOnClick(self.btn_help,  self.OnClickHelp)
    self:RegisterOnClick(self.ShopBtn,  self.OnClickShop)
    self:RegisterOnClick(self.HeroBtn,  self.OnClickHero)

    self:RegisterEvent(Config.EventType.ActivityDrawHeroChoose, self.RefreshData)
    self:RegisterEvent(Config.EventType.Fresh_Bag, self.RefreshData)
end

function _M:OnClickHelp()
    local txts = {}
    txts["title"] = self.tb_activity_model and self.tb_activity_model.f_ExplainTitle
    txts["des"] = self.tb_activity_model and self.tb_activity_model.f_ExplainText
    showUI(PanelNames.CommonTips, txts)
end

function _M:OnClickChooseHero()
    showUI(PanelNames.UIDrawChoose, false, 2, self.activeId)
end

function _M:OnClickShop()
    logicMgr.FuncOpenManager.jump(self.tb_activity_model.f_Functionswitchid, true);
    self:OnBack()
end

function _M:OnClickHero()
    local choose_heroid = drawHandler.ActivityDrawSource.choose_hero_id
    if choose_heroid == nil or choose_heroid == 0 then
        return
    end
    showUI(PanelNames.UIDrawAnimation, choose_heroid, nil, false, function()
        closeUI(PanelNames.UIDrawAnimation)
    end, nil, true, true)
end

function _M:OnClickDraw1()
    local end_time = self.server_activity_data and self.server_activity_data.endTime or 0
    local dis_time =  end_time - Config.serverTime/1000
    if dis_time <= 0 then
        UISysTips.AddMsg(getLanguage("Sys_ActivityEnd"))
        return
    end
    local own_num = logicMgr.ItemManager.getItemCountbyModelId(tostring(self.cost_cfg_item_id1))
    if self.cost_item_num1 > own_num then
        logicMgr.UIShowManager.ShowCommonPop(103, function ()
            self:OnClickShop();
        end);
        --UISysTips.AddMsg(string.format(getLanguage("Character_Tips19"), tostring(self.cost_item_name1) ) )
        return
    end
    drawHandler.reqTimeLimitDraw(self.activeId, self.draw_left_num)
end
function _M:OnClickDraw10()
    local end_time = self.server_activity_data and self.server_activity_data.endTime or 0
    local dis_time =  end_time - Config.serverTime/1000
    if dis_time <= 0 then
        UISysTips.AddMsg(getLanguage("Sys_ActivityEnd"))
        return
    end


    local own_num = logicMgr.ItemManager.getItemCountbyModelId(tostring(self.cost_cfg_item_id2))
    if self.cost_item_num2 > own_num then
        logicMgr.UIShowManager.ShowCommonPop(103, function ()
            self:OnClickShop();
        end);
        --UISysTips.AddMsg(string.format(getLanguage("Character_Tips19"), tostring(self.cost_item_name2)) ) --
        return
    end
    own_num = logicMgr.ItemManager.getItemCountbyModelId(self.quickNumData[1])
    if self.quickNumData[2] <= own_num then
        logicMgr.UIShowManager.ShowCommonPop(104, function ()
            drawHandler.reqTimeLimitDraw(self.activeId, self.quickNumData[3]);
        end , function ()
            drawHandler.reqTimeLimitDraw(self.activeId, self.draw_right_num);
        end, function ()
        end)
    else
        drawHandler.reqTimeLimitDraw(self.activeId, self.draw_right_num)
    end
end

function _M:removeEvent()
end


-- -- 显示
function _M:OnEnable()
    logicMgr.ActiveManager.updateActiveOpenStatus(self.activeId, 2)
end
-- -- 隐藏
-- function _M:OnDisable() 
-- end

-- 卸载
function _M:OnDestroy()
    self.hasInit = nil
    self:CloseTimer()
    self:removeEvent()
    if self._package and UIPackage.GetById(self._package) then
        UIPackage.RemovePackage(self._package)
    end
    self.activeId = nil

    self.btn_help = nil
    self.txt_title = nil
    self.btn_back = nil
    self.com_coin_lb = nil
    self.lihui = nil
    self.btn_draw1 = nil
    self.icon_draw1_cost = nil
    self.txt_draw1_num = nil
    self.txt_draw1_title = nil
    self.btn_draw2 = nil
    self.icon_draw2_cost = nil
    self.txt_draw2_num = nil
    self.txt_draw2_title = nil
    self.txt_change_tips = nil
    self.txt_banner = nil
    self.txt_draw_tips = nil

    self.tb_activity_model = nil
    self.tb_activity = nil
    self.server_activity_data = nil
    drawHandler.ActivityDrawSource = {}
    self.draw_left_num = nil
    self.draw_right_num = nil
    self.cost_cfg_item_id1 = nil
    self.cost_cfg_item_id2 = nil
end

return _M